<?php
namespace App\Service\Admin;

use Illuminate\Support\Facades\DB;

class TmpService extends BaseService
{
    //项目模板

    //列表
    public function getIndex()
    {
        $res = $this->dbConn($this->dbTmp)
            ->where('del', 0)
            ->orderBy('id', 'asc')
            ->get();
        if (!count($res)) {
            return $this->toback(0, '没有项目', []);
        }
        $arys = [];
        foreach ($res as $v) {
            $v = (array) $v;
            $arys[] = [
                'id' => $v['id'],
                'title' => $v['title'],
                'serial' => $v['serial'],
            ];
        }
        return $this->toback(0, '', $arys);
    }

    //详情
    public function getOne($itemId)
    {
        $res = (array) $this->dbConn($this->dbTmp)->where('id', $itemId)->first();
        if (empty($res)) {
            return $this->toback(-2, '没有项目');
        }
        $arys = [
            'id' => $res['id'],
            'title' => $res['title'],
            'serial' => $res['serial'],
        ];
        //文件树
        $frontApi = $this->getDocList($itemId, 1);
        $adminApi = $this->getDocList($itemId, 2);
        $arys['treeList'] = [
            'front_view' => $this->getTree($itemId, 2),
            'front_api' => $frontApi['code']==0 ? $frontApi['data'] : [],
            'admin_view' => $this->getTree($itemId, 1),
            'admin_api' => $adminApi['code']==0 ? $adminApi['data'] : [],
        ];
        return $this->toback(0, '', $arys);
    }

    /**
     * 项目文件树
     * @param int $item_id 项目ID
     * @param int $client_type 1管理后台页面，2管理后台接口，3用户端页面，4用户端接口
     */
    public function getTree($item_id, $client_type, $pid = 0)
    {
        $treeArys = [];
        $res = $this->dbConn($this->dbTmpPath)
            ->where('item_id', $item_id)
            ->where('client_type', $client_type)
            ->where('pid', $pid)
            ->get();
        if (!count($res)) {
            return $treeArys;
        }
        foreach ($res as $v) {
            $v = (array) $v;
            $treeArys[] = [
                'fid' => $v['id'],
                'fname' => $v['title'],
                'fpath' => is_file($v['url']) ? $v['url'] : '',
                'childList' => $this->getTree($item_id, $client_type, $v['id']),
            ];
        }
        return $treeArys;
    }

    /**
     * 保存模板
     * @param array $fs【$fname文件原名, $fpath文件地址, $forigin文件项目名】
     * @param array $pas【type，title】
     */
    public function itemAdd($fs, $pas)
    {
        //前台模板上传
        $rar = $this->dbConn($this->dbTmpRar)->insertGetId([
            'fname' => $fs['fname'], 'fpath' => $fs['fpath'],
            'fitem' => $fs['forigin'], 'addtime' => time(),
        ]);
        if (!$rar) {
            return $this->toback(-1, '前台上传失败');
        }
        //前台模板保存
        if ($pas['title']) {
            $title = $pas['title'];
        } else {
            $fns = explode('.', $fs['fname']);
            $title = $fns[0];
        }
        $serial = toItemSerial();
        $itemid = $this->dbConn($this->dbTmp)->insertGetId([
            'title' => $title, 'serial' => $serial,
            'front_cn' => $fs['fname'], 'front_en' => $fs['forigin'],
            'type' => $pas['type'], 'addtime' => time(),
        ]);
        if (!$itemid) {
            return $this->toback(-1, '前台保存失败');
        }
        $resData = [
            'item_id' => $itemid,
            'serial' => $serial,

        ];
        return $this->toback(0, '', $resData);
    }

    /**
     * 修改模板
     * @param array $fs【$fname文件原名, $fpath文件地址, $forigin文件项目名】
     * @param int $type
     */
    public function itemModify($itemId, $fs)
    {
        //后台模板上传
        $rar = $this->dbConn($this->dbTmpRar)->insertGetId([
            'fname' => $fs['fname'], 'fpath' => $fs['fpath'],
            'fitem' => $fs['forigin'], 'addtime' => time(),
        ]);
        if (!$rar) {
            return $this->toback(-1, '后台上传失败');
        }
        //模板更新
        $item = $this->dbConn($this->dbTmp)->where('id', $itemId)
            ->update([
                'admin_cn' => $fs['fname'], 'admin_en' => $fs['forigin'],
                'uptime' => time(),
            ]);
        if (!$item) {
            return $this->toback(-1, '后台保存失败');
        }
        return $this->toback();
    }

    /**
     * 保存项目文件地址
     * @param string $itemDir 项目地址
     * @param int $item_id 项目ID
     * @param int $clientType 用户端：1用户，2后台
     * @param int $pid 父级ID
     */
    public function addPath($itemDir, $item_id, $clientType, $pid = 0)
    {
        $treeArys = [];
        $trees = scandir($itemDir);
        if (count($trees) <= 2) return false;
        $notIns = [
            '.', '..', 'css', 'fonts', 'js', 'icons', 'images',
            'lib', 'static', 'temp',
        ];
        foreach ($trees as $v) {
            if (!in_array($v, $notIns)) {
                $fDir = $itemDir.'/'.$v;
                $lastid = $this->dbConn($this->dbTmpPath)->insertGetId([
                    'item_id' => $item_id, 'client_type' => $clientType,
                    'title' => $v, 'url' => $fDir,
                    'pid' => $pid, 'addtime' => toDate(),
                ]);
                $childList = [];
                if (is_dir($fDir)) {
                    $childList = $this->addPath($fDir, $item_id, $clientType, $lastid);
                }
                $treeArys[] = [
                    'fid' => $lastid,
                    'fname' => $v,
                    'fpath' => is_file($fDir) ? $fDir : '',
                    'childList' => $childList,
                ];
            }
        }
        return $treeArys;
    }

    //获取文件地址
    public function getFileOne($fid)
    {
        return (array) $this->dbConn($this->dbTmpPath)->where('id', $fid)->first();
    }

    //接口列表
    public function getDocList($item_id, $clientType)
    {
        $res = $this->dbConn($this->dbTmpDoc)
            ->select('id', 'item_id', 'client_type', 'title', 'url', 'req_json')
            ->where('del', 0)
            ->where('item_id', $item_id)
            ->where('client_type', $clientType)
            ->get();
        if (!count($res)) {
            return $this->toback(-2, '没有文档数据');
        }
        foreach ($res as $k => $v) {
            $reqJsons = $v->req_json ? json_decode($v->req_json, true) : [];
            $res[$k]->url = env('DOMAIN').$v->url;
            $res[$k]->req_json = $reqJsons;
        }
        return $this->toback(0, '', $res);
    }

    /**
     * 拷一份项目
     * @param int $uid 用户ID
     * @param int $item_id 项目模板ID
     */
    public function copyByUid($uid, $item_id)
    {
        $userItemId = 0; //用户项目ID
        //复制项目
        $xmItemOne = (array) $this->dbConn($this->dbXm)
            ->where('del', 0)
            ->where('uid', $uid)
            ->where('tmp_id', $item_id)
            ->first();
        $itemOne = (array) $this->dbConn($this->dbTmp)
            ->where('del', 0)
            ->where('id', $item_id)
            ->first();
        if (empty($xmItemOne) && !empty($itemOne)) {
            $userItemId = $this->dbConn($this->dbXm)->insertGetId([
                'uid' => $uid, 'tmp_id' => $item_id, 'title' => $itemOne['title'],
                'addtime' => toDate(), 'uptime' => toDate(),
            ]);
        }
        //复制目录
        $xmPathTotal = $this->dbConn($this->dbXmPath)
            ->where('del', 0)
            ->where('id', $item_id)
            ->count();
        $pathOnes = $this->dbConn($this->dbTmpPath)
            ->where('del', 0)
            ->where('item_id', $item_id)
            ->get();
        if ($userItemId && !$xmPathTotal && count($pathOnes)) {
            foreach ($pathOnes as $v) {
                $v = (array) $v;
                $this->dbConn($this->dbXmPath)->insertGetId([
                    'uid' => $uid, 'tmp_id' => $item_id, 'tmp_path_id' => $v['id'],
                    'user_item_id' => $userItemId, 'client_type' => $v['client_type'],
                    'title' => $v['title'], 'url' => $v['url'], 'pid' => $v['pid'],
                    'addtime' => toDate(), 'uptime' => toDate(),
                ]);
            }
        }
        //复制菜单
        $xmMenuTotal = $this->dbConn($this->dbXmMenu)->count();
        if ($userItemId && !$xmMenuTotal) {
            $this->copyMenu($uid, $item_id, $userItemId);
        }
        //复制用户
        $xmUserOnes = $this->dbConn($this->dbXmUser)->get();
        if ($userItemId && !count($xmUserOnes)) {
            $userOnes = $this->dbConn($this->dbTmpUser)->get();
            if (count($userOnes)) {
                foreach ($userOnes as $v) {
                    $v = (array) $v;
                    $this->dbConn($this->dbXmUser)->insertGetId([
                        'uid' => $uid, 'tmp_id' => $item_id, 'tmp_user_id' => $v['id'],
                        'user_item_id' => $userItemId, 'type' => 2, 'nick' => $v['nick'],
                        'passwd' => md5('123456'), 'phone' => $v['phone'],
                        'addtime' => toDate(), 'uptime' => toDate(),
                    ]);
                }
            }
        }
        //复制文档
        $xmDocOnes = $this->dbConn($this->dbXmDoc)->get();
        if ($userItemId && !count($xmDocOnes)) {
            $userDocOnes = $this->dbConn($this->dbTmpDoc)->where('del', 0)->get();
            if (count($userDocOnes)) {
                foreach ($userDocOnes as $v) {
                    $v = (array) $v;
                    $this->dbConn($this->dbXmDoc)->insertGetId([
                        'uid' => $uid, 'tmp_id' => $item_id, 'tmp_doc_id' => $v['id'],
                        'user_item_id' => $userItemId, 'client_type' => $v['client_type'],
                        'title' => $v['title'], 'url' => $v['url'], 'req_json' => $v['req_json'],
                        'del' => $v['del'], 'addtime' => toDate(), 'uptime' => toDate(),
                    ]);
                }
            }
        }
        return true;
    }

    /**
     * 递归复制菜单
     * @param int $uid 用户ID
     * @param int $itemId 模板项目ID
     * @param int $userItemId 用户项目ID
     * @param int $pid 菜单父ID
     */
    public function copyMenu($uid, $itemId, $userItemId, $pid = 0)
    {
        $menuOnes = $this->dbConn($this->dbTmpMenu)
            ->where('item_id', $itemId)
            ->where('pid', $pid)
            ->get();
        if (!count($menuOnes)) {
            return false;
        }
        foreach ($menuOnes as $v) {
            $v = (array) $v;
            $this->dbConn($this->dbXmMenu)->insertGetId([
                'uid' => $uid, 'tmp_id' => $itemId, 'tmp_menu_id' => $v['id'],
                'user_item_id' => $userItemId, 'type' => $v['type'],
                'title' => $v['title'], 'icon' => $v['icon'], 'link' => $v['link'],
                'pid' => $v['pid'], 'is_show' => $v['is_show'],
                'addtime' => toDate(), 'uptime' => toDate(),
            ]);
            //复制数据
            $xmDataTotal = $this->dbConn($this->dbXmData)->where('menu_id', $v['id'])->count();
            if (!$xmDataTotal) {
                $tmpDataOnes = $this->dbConn($this->dbTmpData)->where('menu_id', $v['id'])->get();
                foreach ($tmpDataOnes as $vv) {
                    $vv = (array) $vv;
                    $this->dbConn($this->dbXmData)->insertGetId([
                        'uid' => $uid, 'tmp_id' => $itemId, 'tmp_data_id' => $vv['id'],
                        'user_item_id' => $userItemId, 'type' => $vv['type'], 'menu_id' => $vv['menu_id'],
                        'field_cn' => $vv['field_cn'], 'field_en' => $vv['field_en'],
                        'field_type' => $vv['field_type'], 'field_val' => $vv['field_val'],
                        'disabled' => $vv['disabled'], 'tmp_menu_id' => $vv['id'],
                        'addtime' => toDate(), 'uptime' => toDate(),
                    ]);
                }
            }
            //查看下级
            $this->copyMenu($uid, $itemId, $userItemId, $v['id']);
        }
        return true;
    }
}